"use client"
import { createContext, useEffect, useMemo, useState } from "react";
import { BoxData, NodeMapContext } from "./NodeMapContext";
import { useDragDropManager } from "react-dnd";


export const NodeMapProvider = ({ children }: { children: React.ReactNode }) => {



  const [boxIndex, setBoxIndex] = useState<Record<string, string[]>>({});
  const [boxData, setBoxData] = useState<Map<string, BoxData>>(new Map());

  // 更新 boxData 和 boxIndex
  const handSetBox = (item: any, monitor: any, parentId: string) => {
    if (!monitor.isOver({ shallow: true })) return //鼠标在容器内触发
    if (monitor.didDrop()) return;
    // console.log(item)
    // console.log(monitor)
    // if (boxIndex[parentId]?.includes(item.id)) return
    console.log("parentId",item, parentId,boxIndex)

    setBoxData(prev => {
      const newMap = new Map(prev);
      newMap.set(item.id, { ...item, targetId: monitor.targetId, parentId }); // 或者更新后的值
      return newMap;
    });
    if (item.targetId === undefined) {
      setBoxIndex((prev) => ({
        ...prev,
        [parentId]: [...(prev[parentId] || []), item.id],
      }));
    }
    if (item.targetId && item.targetId !== monitor.targetId) {
      console.log("monitor", item, monitor)
      setBoxIndex((prev) => ({
        ...prev,
        [item.parentId]: [...(prev[item.parentId].filter(it => it !== item.id) || [])],
        [parentId]: [...(prev[parentId] || []), item.id],
      }));
    }
    if (item.targetId && item.targetId == monitor.targetId) {

    }

  };

  // 优化性能：避免不必要的重渲染
  const value = useMemo(() => ({ boxData, boxIndex, handSetBox }), [boxData, boxIndex]);

  return (
    <NodeMapContext.Provider value={value}>
      {children}
    </NodeMapContext.Provider>
  );
};